import type { UploadFile } from "element-plus";
import jsQR from "jsqr";
/**
 * @description 验证文件格式
 * @param {String | Array} fileAccept 例'.pdf,.png'
 * @param {UploadFile | file} file 支持 elementUI封装过的文件对象 和 原生文件对象
 * @returns {Blooen}
 */
export function verifyFileFormat(fileAccept: string, file: UploadFile): boolean {
	let accept = [];
	if (typeof fileAccept === "string") {
		accept = fileAccept.split(",");
	} else {
		accept = fileAccept;
	}
	let fileExtensions = file.name.split(".")[file.name.split(".").length - 1];
	if (fileAccept === "*") return true;
	if (file?.raw) {
		if (accept.indexOf("." + fileExtensions) < 0 && accept.indexOf(file.raw.type) < 0) {
			return false;
		} else {
			return true;
		}
	} else {
		return false;
	}
}
// 手机号正则验证
export function mphoneValidator(value: string) {
	const reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
	if (value && !reg.test(value)) {
		return false;
	} else {
		return true;
	}
}
// 比特转兆比特
export function b2mb(b: number): number {
	return Number((b / 1024 / 1024).toFixed(2));
}
// 判断设备是否横屏
export function isOrientationLandscape() {
	return window.matchMedia("(orientation: landscape)").matches;
}

// 复制文本到剪切板
export function copyText(text: string, isTip: boolean = false, msg: string = "已成功复制到剪切板") {
	// navigator clipboard 需要https等安全上下文
	if (navigator.clipboard && window.isSecureContext) {
		// navigator clipboard 向剪贴板写文本
		ElMessage({
			message: msg,
			type: "success",
		});
		return navigator.clipboard.writeText(text);
	} else {
		// document.execCommand('copy') 向剪贴板写文本
		let input = document.createElement("input");
		input.style.position = "fixed";
		input.style.top = "-10000px";
		input.style.zIndex = "-999";
		document.body.appendChild(input);
		input.value = text;
		input.focus();
		input.select();
		try {
			let result: any = document.execCommand("copy");
			document.body.removeChild(input);
			console.log(result);
			if (!result || result === "unsuccessful") {
				console.log("复制失败");
				ElMessage({
					message: "复制失败，请手动复制",
					type: "error",
				});
			} else {
				ElMessage({
					message: msg,
					type: "success",
				});
			}
		} catch (e) {
			document.body.removeChild(input);
			alert("当前浏览器不支持复制功能，请检查更新或更换其他浏览器操作");
		}
	}
}

// 对象转url参数用于拼接到url
export function objectToQuery(value: object, prefixstring?: string): string {
	let obj = arguments[0];
	let prefix = arguments[1];
	if (typeof obj !== "object") return "";
	const attrs = Object.keys(obj);
	return attrs.reduce((query, attr, index) => {
		// 判断是否是第一层第一个循环
		if (index === 0 && !prefix) query += "?";
		if (typeof obj[attr] === "object") {
			const subPrefix = prefix ? `${prefix}[${attr}]` : attr;
			query += objectToQuery(obj[attr], subPrefix);
		} else {
			if (prefix) {
				query += `${prefix}[${attr}]=${obj[attr]}`;
			} else {
				query += `${attr}=${decodeURI(obj[attr])}`;
			}
		}
		// 判断是否是第一层最后一个循环
		if (index !== attrs.length - 1) query += "&";
		return query;
	}, "");
}

export function searchParamToObj(url = location.href) {
	return Object.fromEntries(new URL(url).searchParams);
}

// 文件转base64
export function FileToBase64(file: any): Promise<string> {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		let fileResult = "" as string;
		reader.readAsDataURL(file);
		reader.onload = () => {
			fileResult = String(reader.result);
		};
		reader.onerror = (error: any) => {
			reject(error);
		};
		reader.onloadend = () => {
			resolve(fileResult);
		};
	});
}
// base64转文件
export function base64ToFile(urlData: any, fileName: string) {
	let arr = urlData.split(",");
	let mime = arr[0].match(/:(.*?);/)[1];
	let bytes = atob(arr[1]); // 解码base64
	let n = bytes.length;
	let ia = new Uint8Array(n);
	while (n--) {
		ia[n] = bytes.charCodeAt(n);
	}
	return new File([ia], fileName, { type: mime });
}
// 文件转二进制
export function fileToBindary(file: File) {
	return new Promise<any>((resolve, reject) => {
		const reader = new FileReader();
		reader.onload = function (e: any) {
			const arrayBuffer = e.target.result;
			const uint8Array = new Uint8Array(arrayBuffer);
			// 现在uint8Array就是文件的二进制流
			// console.log(uint8Array);
			resolve(uint8Array);
		};
		reader.readAsArrayBuffer(file);
	});
}

export function decodeQRFromBase64(base64String: string) {
	return new Promise<any>((resolve, reject) => {
		var objCanvas: any = document.createElement("canvas");
		var ctx = objCanvas.getContext("2d"); // 返回值是CanvasRenderingContext2D类的对象实例。
		var image = new Image();
		image.src = base64String;
		image.onload = function () {
			ctx.drawImage(image, 0, 0, image.width, image.height); // 绘图
			var imageData = ctx.getImageData(0, 0, image.width, image.height);
			// QR码解析
			const code = jsQR(
				imageData.data, // 图像数据
				imageData.width, // 宽度
				imageData.height, // 高度
				{
					// 可选的对象
					inversionAttempts: "dontInvert",
				}
			);
			if (code) {
				resolve(code);
			} else {
				reject();
			}
		};
	});
}
